#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "aboutdialog.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    t = new QTimer(this);
    record = false;
    ui->setupUi(this);
    play = false;
    paused = false;
    currentFrame = 0;

    QGraphicsScene *scene = new QGraphicsScene();

    ui->graphicsView->setScene(scene);



    ui->chkBottomLight->setChecked(Qx3Model::getInstance()->getBottomLight());
    ui->chkTopLight->setChecked(Qx3Model::getInstance()->getTopLight());

    // Setup the image settings
   ui->slideBrightness->setValue(Qx3Model::getInstance()->getBrightness());
   ui->slideContrast->setValue(Qx3Model::getInstance()->getContrast());
   ui->slideColor->setValue(Qx3Model::getInstance()->getColor());
   ui->slideBlueGain->setValue(Qx3Model::getInstance()->getBlueGain());
   ui->slideRedGain->setValue(Qx3Model::getInstance()->getRedGain());
   ui->slideGreenGain->setValue(Qx3Model::getInstance()->getGreenGain());
   ui->slideQuality->setValue(Qx3Model::getInstance()->getQuality());

   ui->slideRedGain->setScale(0,212);
   ui->slideRedGain->setRange(0,212,1,1);
   ui->slideBlueGain->setScale(0,212);
   ui->slideBlueGain->setRange(0,212,1,1);
   ui->slideGreenGain->setScale(0,212);
   ui->slideGreenGain->setRange(0,212,1,1);

   connect(Qx3Model::getInstance(), SIGNAL(buttonPressed()), this, SLOT(on_Qx3Model_buttonPressed()));
   connect(Qx3Model::getInstance(), SIGNAL(cradleChanged(bool)), this, SLOT(on_Qx3Model_cradleChanged(bool)));
    // Use a time to repeatedly update the image
    t = new QTimer(this);
   connect( t, SIGNAL(timeout()), SLOT(on_t_timeout()) );

   this->on_chkFreeze_toggled(false);

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::closeEvent(QCloseEvent *)
{
    Qx3Model::getInstance()->setTopLight(false);
    Qx3Model::getInstance()->setBottomLight(false);
}

void MainWindow::on_Qx3Model_buttonPressed(){

    QString filename(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss.png"));
    QImage img = gvPixmap->pixmap().toImage();
//    img.convertDepth(8);
    img.save(filename,"PNG",0);



    qDebug(qPrintable(QString("ButtonPressed")));
}

void MainWindow::on_Qx3Model_cradleChanged(bool cradlestate){
    if(!cradlestate){
        if(ui->chkBottomLight->isChecked()) {
            ui->chkBottomLight->setChecked(false);
            ui->chkTopLight->setChecked(true);
        }
    }
}


void MainWindow::on_chkTopLight_toggled( bool state ) {
    if(Qx3Model::getInstance()->getBottomLight()) ui->chkBottomLight->setChecked(false);
    Qx3Model::getInstance()->setTopLight( state );
}

void MainWindow::on_chkBottomLight_toggled( bool state ) {
    if(Qx3Model::getInstance()->getTopLight()) ui->chkTopLight->setChecked(false);
    Qx3Model::getInstance()->setBottomLight( state );
}

//void MainWindow::on_frame_captured(const char *frame)
//{
//    const uchar* data = (const uchar*)frame;
//    QImage image(const_cast<uchar*>(data), 352, 288, QImage::Format_RGB888);
//    //image.invertPixels(QImage::InvertRgb);
//    QGraphicsScene *scene = ui->graphicsView->scene();
//    scene->clear();
//
//    gvPixmap = scene->addPixmap(QPixmap::fromImage(image));
//}

void MainWindow::on_t_timeout() {
        // Nothing fancy here - if not frozen, get the array of bytes and
        // create a QImage (which does the hard work) and then apply it to
        // the label
        // TODO:  Double buffering - prob override paint of label///
    const uchar* data;
    QImage image;


    if(!play){
        data = (const uchar*)Qx3Model::getInstance()->getFrame();
        image = QImage(const_cast<uchar*>(data), 352, 288, QImage::Format_RGB888);
        QGraphicsScene *scene = ui->graphicsView->scene();
        scene->clear();
        gvPixmap = scene->addPixmap(QPixmap::fromImage(image.scaled(704, 578, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
    }
   else
   {
        if(!paused && decoder.seekNextFrame()) //videoReader.grab(rImage))
        {

            // Decode a frame
            int et,en;
            if(!decoder.getFrame(image,&en,&et))
            {

            }
            ui->slideVideoPosition->setValue(et);
            QGraphicsScene *scene = ui->graphicsView->scene();
            scene->clear();
            gvPixmap = scene->addPixmap(QPixmap::fromImage(image.scaled(704, 578, Qt::KeepAspectRatio, Qt::SmoothTransformation)));
        }
        else // We reached the end, but still in play mode
        {
            //play = false;
            paused = true;
            ui->slideVideoPosition->setEnabled(true);
            ui->btnPlay->setText("Play");

            this->on_chkFreeze_toggled(true);
        }
    }
    if(record)
    {
        encoder.encodeImage(image.convertToFormat(QImage::Format_RGB32));
    }
}
void MainWindow::on_slideBrightness_valueChanged( int  brightness) {
        Qx3Model::getInstance()->setBrightness(static_cast<uint>(brightness));
}

void MainWindow::on_slideColor_valueChanged( int color) {
        Qx3Model::getInstance()->setColor(static_cast<uint>(color));
}

void MainWindow::on_slideContrast_valueChanged( int contrast) {
        Qx3Model::getInstance()->setContrast(static_cast<uint>(contrast));
}

void MainWindow::on_slideRedGain_valueChanged(double redGainValue)
{
    Qx3Model::getInstance()->setRedGain(redGainValue);
}

void MainWindow::on_slideGreenGain_valueChanged(double greenGainValue)
{
    Qx3Model::getInstance()->setGreenGain(greenGainValue);
}
void MainWindow::on_slideBlueGain_valueChanged(double blueGainValue)
{
    Qx3Model::getInstance()->setBlueGain(blueGainValue);
}

void MainWindow::on_slideQuality_valueChanged(int quality){
    Qx3Model::getInstance()->setQuality(quality);
}

void MainWindow::on_chkFreeze_toggled( bool freeze ) {
  if(freeze) {
    //  disconnect(Qx3Model::getInstance(), SIGNAL(frame_captured(const char *)), this, SLOT(on_frame_captured(const char *)));
    t->stop();
  }
  else {
    //connect(Qx3Model::getInstance(), SIGNAL(frame_captured(const char *)), this, SLOT(on_frame_captured(const char *)));
    t->start( 33 );
  }
}

void MainWindow::on_btnSnap_clicked(){
  if(!ui->chkFreeze->isChecked())
    ui->chkFreeze->setChecked(true);

  QString s = QFileDialog::getSaveFileName(this, "Save File Dialog",".", "Images (*.png)");
  if( !s.isEmpty() || !s.isNull()) {
    if(!s.toLower().endsWith(".png")) {
      s+=".png";
    }
    QImage img = gvPixmap->pixmap().toImage();
//    img.convertDepth(8);
    img.save(s,"PNG",0);
  }
  ui->chkFreeze->setChecked(false);
}

void MainWindow::on_actionAbout_triggered(){
    AboutDialog about;

    about.exec();


}

void MainWindow::on_btnRecord_clicked()
 {

//    videoFile = new QFile("/tmp/test.yuv");
 //   videoFile->open(QIODevice::WriteOnly|QIODevice::Truncate);
	currentFileName = QFileDialog::getSaveFileName(this, tr("Save File"), "~", tr("Video (*.avi)"));

    encoder.createFile(currentFileName,352,288,1000000,20);
//    writeYUV4MPEG2Header(*videoFile, 352, 288, 24);
    this->record = true;
    ui->btnRecord->setEnabled(false);
    ui->btnStop->setEnabled(true);
    ui->btnPlay->setEnabled(false);

 }

void MainWindow::on_btnStop_clicked()
{
    if(record){
//        videoFile->close();
        this->record = false;
        ui->btnRecord->setEnabled(true);
        ui->btnStop->setEnabled(false);
        ui->btnPlay->setEnabled(true);
        encoder.close();
    }

    if(play)
    {
        //videoReader.close();
        play = false;
        paused = false;
        ui->btnPlay->setText("Play");
        ui->btnPlay->setEnabled(true);
        ui->btnStop->setEnabled(false);
        ui->slideVideoPosition->setEnabled(false);
        currentFrame = 0;
        ui->slideVideoPosition->setValue(0);
        this->on_chkFreeze_toggled(false);
        decoder.close();

    }
}

void MainWindow::on_slideVideoPosition_valueChanged(double position)
{

    if(play && !paused) return;

    currentFrame = position;

    decoder.seekMs(position);

    int et,en;
    QImage image;
    if(!decoder.getFrame(image,&en,&et))
    {

    }
    QGraphicsScene *scene = ui->graphicsView->scene();
    scene->clear();
    gvPixmap = scene->addPixmap(QPixmap::fromImage(image.scaled(704, 578, Qt::KeepAspectRatio, Qt::SmoothTransformation)));


}

void MainWindow::on_btnPlay_clicked()
{

    if(ui->btnPlay->text() == "Play"){
        this->on_chkFreeze_toggled(true);
        //if (!videoReader.open("/tmp/test.yuv",QVMPlayerReader::NoLoop))

        if(currentFileName.isNull() && currentFileName.isEmpty())
        {
        	currentFileName = QFileDialog::getOpenFileName(this, tr("Open File"), "~", tr("Video (*.avi)"));
        }
    	if(!decoder.openFile(currentFileName))
        {
            play = false;
        }
        else
        {
            play = true;
            paused = false;
            record = false;
            ui->btnStop->setEnabled(true);
            ui->slideVideoPosition->setEnabled(false);
            ui->btnPlay->setText("Pause");
            framenumber = 0;

           ui->slideVideoPosition->setRange(0,decoder.getVideoLengthMs(),1,1);
           decoder.seekMs(ui->slideVideoPosition->value());

        }
        this->on_chkFreeze_toggled(false);
    }
    else if(ui->btnPlay->text() == "Pause")
    {
        paused = true;
        ui->btnPlay->setText("Play");
        ui->slideVideoPosition->setEnabled(true);
        this->on_chkFreeze_toggled(true);
    }


}
